const express = require("express");
const router = express.Router();
const AccountModel = require("../../models/AccountModel");
const checkTokenMiddleware = require("../../middlewares/checkTokenMiddleware");


// 添加
router.post("/add", checkTokenMiddleware, (req, res) => {
    // 获取登录人的用户id，作为userId的参数
    let userId = req.user._id;
    // res.end("444");
    // return;
    AccountModel.create({ ...req.body, userId: userId }).then(data => {
        res.json({
            code: "10000",
            message: "添加成功",
            data: data
        })
    }).catch(() => {
        res.json({
            code: "2002",
            message: "调用接口失败",
            data: null
        })
    })
})

// 查询列表
router.get("/account", checkTokenMiddleware, (req, res) => {
    let userId = req.user._id;
    AccountModel.find({ userId: userId }).exec().then((data) => {
        // 按照从小到大顺序排列
        const aa = data.sort((a, b) => new Date(a.time) - new Date(b.time));
        res.json({
            code: "10000",
            message: "成功",
            data: aa
        })
    }).catch(err => {
        res.json({
            code: "2002",
            message: "调用接口失败",
            data: null
        })
    })
})

// 删除账单列表
router.delete("/delete/:id", checkTokenMiddleware, (req, res) => {
    let { id } = req.params;
    AccountModel.deleteOne({ _id: id }).then(data => {
        res.json({
            code: "10000",
            message: "成功",
            data: data
        })
    }).catch(() => {
        res.json({
            code: "2002",
            message: "调用接口失败",
            data: null
        })
    })
})
// 修改账单列表
router.patch("/update/:id", checkTokenMiddleware, (req, res) => {
    let userId = req.user._id;
    let { id } = req.params;
    req.body = { ...req.body, userId }
    AccountModel.updateMany({ _id: id }, req.body).then(data => {
        console.log(data);
        res.json({
            code: "10000",
            message: "成功",
            data: data
        })
    }).catch(err => {
        res.json({
            code: "2002",
            message: "调用接口失败",
            data: null
        })
    })
})

module.exports = router;